<?php
/**
 * Created by PhpStorm.
 * User: fuckrm
 * Date: 17-9-13
 * Time: 下午3:05
 */

/**
 * @param $value
 * @return mixed
 */
function roundPercentage($value)
{
    return maxZero(mround($value * 100, 2));
}

/**
 * 计算进度
 *
 */
function progress($total_tender, $transfer_money)
{

    return (int)(($total_tender / $transfer_money) * 100);
}

/**
 * 计算万元收益
 * @param apr 年华收益率
 * @param cycle 未还款期数
 * @return fload
 */
function earnings($apr, $cycle)
{
    return mround(10000 * $apr * $cycle / 12, 2);
}

/**
 * 如果小于0返回0
 * @param $value
 * @return mixed
 */
function maxZero($value)
{
    return max(0, $value);
}

/**
 * 四舍五入
 * @param $val
 * @param int $f
 * @return string
 */
function mround($val, $f = 2)
{
    if (is_null($val)) {
        return '0.00';
    }
    return number_format($val, $f, '.', '');
}

function getUserID()
{

    if (!app()->isLocal()) {
        return JWTAuth::parseToken()->getPayload()->get('sub');
    }
    return '98';
}

function createLinkstringUrlencode($para)
{
    $arg = "";
    foreach ($para as $key => $val) {
        $arg .= $key . "=" . urlencode($val) . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, strlen($arg) - 2);

    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }

    return $arg;
}

function paraFilter($para)
{
    $para_filter = array();
    foreach ($para as $key => $val) {
        if ($key == "sign" || $val == "") continue;
        else  $para_filter[$key] = $para[$key];
    }
    return $para_filter;
}

function argSort($para)
{
    ksort($para);
    reset($para);
    return $para;
}

/**
 * 比较数字
 * @param $num1
 * @param string $opera 可用 '=', '>', '<', '>=', '<='
 * @param int $num2
 * @return bool|int
 */
function compareNumber($num1, $opera = '=', $num2 = 0)
{
    switch ($opera) {
        case '=':
            return $num1 = $num2;
        case '>':
            return $num1 > $num2;
        case '<':
            return $num1 < $num2;
        case '>=':
            return $num1 >= $num2;
        case '<=':
            return $num1 <= $num2;
        default:
            return false;
    }
}

/**
 * 数字单位赚中文
 * @param $number
 * @return string
 */
function numberUnit2chinese($number)
{
    // 多少亿
    $yi = 0;
    if ($number >= 100000000) {
        $yi = floor($number / 100000000);
        // 剩余数量
        $number = $number % 100000000;
    }

    // 多少万
    $wan = 0;
    if ($number >= 10000) {
        // 多少万
        $wan = floor($number / 10000);
        // 剩余数量
        $number = $number % 10000;
    }

    // 多少元
    $yuan = floor($number);
    $str = '';
    if ($yi > 0) {
        $str .= "{$yi}亿";
    }
    if ($wan > 0) {
        $str .= "{$wan}万";
    }
    if ($yuan > 0) {
        $str .= "{$yuan}元";
    }
    return $str;
}

/**
 * 格式化姓名
 * @param $name
 * @return string
 */
function formatRealname($name)
{
    return str_repeat('*', mb_strlen($name) - 1) . mb_substr($name, -1);
}

/**
 * 格式化手机号
 * @param $str
 * @return mixed
 */
function formatPhone($str)
{
    $resstr = substr_replace($str, '****', 3, 4);
    return $resstr;
}

/**
 * 处理时间
 * @param $condition
 * @param $timestamp
 * @return false|string
 */
function dueDate($condition, $timestamp)
{
    return $condition ? date('Y-m-d', $timestamp) : '/';
}

/**
 * 折让金额
 * @param $money
 * @param $percent
 * @return float|int
 */
function moneyPercent($money, $percent)
{
    return $money * (1 - $percent);
}
/**
 * 计算俩个日期相差天数
 * @name diffDate
 * @param array
 * @author Mr.Liu
 * @return JsonStr
 * @datetime 2018/7/4 14:25
 */
function diffDate($date1,$date2=''){
    if(empty($date2)){
        $date2 = time();
    }
    if($date1>$date2){
        $tmp=$date2;
        $date2=$date1;
        $date1=$tmp;
    }
    list($Y1,$m1,$d1)=explode('-',date('Y-m-d H:i:s',$date1));
    list($Y2,$m2,$d2)=explode('-',date('Y-m-d H:i:s',$date2));
    $y=intval($Y2)-intval($Y1);
    $m=intval($m2)-intval($m1);
    $d=intval($d2)-intval($d1);
    if($d<0){
        $d+=(int)date('t',strtotime("-1 month $date2"));
        $m--;
    }
    if($m<0){
        $m+=12;
        $y--;
    }

    if($y>0){
        $m+=(12*$y);
    }

    return ['month'=>$m,'day'=>$d];
}



/**
 * @param $path
 * @return bool
 * 递归方式创建目录
 */
function make_dirs($path) {
    if (!is_dir($path)) {
        make_dirs(dirname($path));
        mkdir($path);
    }
    return is_dir($path);
}

/**
 * 替换特殊字符
 * @name ext_json_decode
 * @param * @param $str
 * @param bool $mode
 * @author Mr.Liu
 * @return
 * @datetime 2018/10/16 11:34
 */
function ext_json_decode($str, $mode = true){
    $str = htmlspecialchars_decode($str);
    $str = preg_replace('/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/','$1"$3":',$str);
    $str = str_replace('\'','"',$str);
    $str = str_replace(" ", "", $str);
    $str = str_replace("\t", "", $str);
    $str = str_replace("\r", "", $str);
    $str = str_replace("\n", "", $str);
    //$str = str_replace("\l", "", $str);
    //$str = preg_replace('/s+/', '',$str);
    $str = trim($str,chr(239).chr(187).chr(191));

    return json_decode($str, $mode);
}

/**
 * 替换特殊字符
 * @name ext_str
 * @param * @param $str
 * @param bool $mode
 * @author Mr.Liu
 * @return
 * @datetime 2018/10/16 11:35
 */
function ext_str($str){
//    $str = str_replace('\'','"',$str);
//    $str = str_replace(" ", "", $str);
//    $str = str_replace("\t", "", $str);
//    $str = str_replace("\r", "", $str);
    $str = str_replace("\n", "", $str);

    return $str;
}


function extend_config($sign = null, $columns = ['*']){

    $model = new \App\Models\Config();

    if(!is_null($sign)){
        $data = $model->whereSign($sign)->select($columns)->first();
    }else{
        $data = $model->select($columns)->get();
    }

    return $data;
}

/**
 * 生成订单号
 * @return string  订单号
 */
function create_hf_no()
{
    list($tmp1, $tmp2) = explode(' ', microtime());
    $msec = substr(($tmp1 * 10000000), 3, 3);
    return date('YmdHis', time()) . $msec . rand(1000, 9999);
}

/**
 * 生成批量操作子订单号
 */
function create_detail_no()
{
    list(, $haoma) = explode('.', microtime(true));
    $str = str_pad($haoma, 4, "0", STR_PAD_RIGHT);

    return date("YmdHis", time()) . $str . rand(10, 99);
}


//$m和$n代表传入的两个数值，主要就是这两个数值之间的比较
//$x代表传入的方法，比如是；add,sub等
//$scale  代表传入的小数点位数。这个根据需求更改即可
function calc($m,$n,$x,$scale){
    $errors=array(
        '被除数不能为零',
        '负数没有平方根'
    );
    switch($x){
        case 'add':
            $t=bcadd($m,$n,$scale);
            break;
        case 'sub':
            $t=bcsub($m,$n,$scale);
            break;
        case 'mul':
            $t=bcmul($m,$n);
            break;
        case 'div':
            if($n!=0){
                $t=bcdiv($m,$n);
            }else{
                return $errors[0];
            }
            break;
        case 'pow':
            $t=bcpow($m,$n);
            break;
        case 'mod':
            if($n!=0){
                $t=bcmod($m,$n);
            }else{
                return $errors[0];
            }
            break;
        case 'sqrt':
            if($m>=0){
                $t=bcsqrt($m);
            }else{
                return $errors[1];
            }
            break;
    }
    return $t;
}

function GetConfigValue($name = null){
    return \Illuminate\Support\Facades\DB::table('config')->where('name',$name)->value('value');
}

function getAppUrl(){
    return trim(env('APP_URL'),'/').'/';
}

function getRoleList(){
    $roleList = \Illuminate\Support\Facades\DB::table('roles')
        ->select('id','name')
        ->where('id', '<>', 1)
        ->get()
        ->mapWithKeys(function($item){
            return [$item->id => $item->name];
        });

    return $roleList;
}

function getRole($id){
    return  \Illuminate\Support\Facades\DB::table('roles')
        ->where('id', '=', $id)
        ->value('name');
}

/**
 * 获取跳转JSON数据
 * @name getJumUrlList
 * @param array
 * @author Mr.Liu
 * @return JsonStr
 * @datetime 2019/5/21 15:03
 */
function getJumUrlList(){

    $json = [[
        'name'          => '商品列表',
        'type'         => 'optgroup'
    ]];

    \Illuminate\Support\Facades\DB::table('goods_home')
        ->where('status',\App\Models\GoodsHome::STATUS_OPEN)
        ->select('id','module')
        ->get()
        ->each(function($item)use(&$json){
            $json[] = [
                'name'          => $item->module,
                'value'         => "/pages/goodsList/goodsList?activityId={$item->id}",
            ];
        });

    array_push($json,[
            'name'          => '活动',
            'type'         => 'optgroup'
        ]);

    \Illuminate\Support\Facades\DB::table('activity')
        ->where('status',\App\Models\Activity::statusTrue)
        ->select('id','activity_name','jump_url')
        ->get()
        ->transform(function($item)use(&$json){
            $json[] = [
                'name'          => $item->activity_name,
                'value'         => $item->jump_url,
            ];
        });

    array_push($json,[
            'name'          => '其它',
            'type'         => 'optgroup'
        ],
        [
            'name'          => '会员充值界面',
            'value'         => '/pages/recharge/index',
        ],
        [
            'name'          => '商品详情页',
            'value'         => false,
            'tableSelect'   => 'goodsList',
        ],
        [
            'name'          => '贝壳余额页面',
            'value'         => '/pages/dreamBox/my_shell/my_shell',
        ],
        [
            'name'          => '会员权益页面',
            'value'         => '/pages/account/vip',
        ],
        [
            'name'          => '关于我们页面',
            'value'         => '/pages/my/join',
        ],
        [
            'name'          => '邀请好友页面',
            'value'         => '/pages/my/invite',
        ]);


    return $json;
}

if (!function_exists('w_log')) {
    /**
     * 记录文本log
     * @param string $msg 信息
     * @param string $url 路径
     */
    function w_log($msg = "", $url = "")
    {

        if (!is_dir(storage_path('logs/data/') . $url)) {
            mkdir(storage_path('logs/data/') . $url, 0777, true);
        }
        if (is_dir(storage_path('logs/data/') . $url)) {
            $msg = date("Y-m-d H:i:s") . "|" . $msg . "\r\n\r\n";
            file_put_contents(storage_path('logs/data/') . $url . "/" . date("Ymd", time()) . ".log", $msg, FILE_APPEND);
        }
    }
}
if (!function_exists('curlGet')) {
    /**
     * curl请求get方式
     * @param $url
     * @return mixed
     */
    function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        if (!($output = curl_exec($ch))) {
            file_put_contents("log-curl" . date('Y-m-d') . ".error", "Curl错误:" . curl_error($ch) . "\n", FILE_APPEND);
            return false;
        }
        curl_close($ch);
        return $output;
    }
}

if (!function_exists('curlPost')) {
    /**
     * curl POST
     * @param string $url
     * @param string $postData
     * @param array $options
     * @return mixed
     */
    function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (!($data = curl_exec($ch))) {
            file_put_contents("log-curl" . date('Y-m-d') . ".error", "Curl错误:" . curl_error($ch) . "\n", FILE_APPEND);
            return false;
        }
        curl_close($ch);

        return $data;
    }
}

if (!function_exists('numberFormat')) {
    /*
     * 数字格式化函数 不四舍五入
     * */
    function numberFormat($number, $precision = 2)
    {
        return number_format(round($number,$precision),$precision,'.','');
    }
}

if(!function_exists('sprintfFormat')){
    /*
     * 数字格式化函数 四舍五入
     * */
    function sprintfFormat($number,$precision = 2){
        return number_format(round($number,$precision),$precision,'.','');
    }
}


